#include "include/settings.h"
#include "include/parser.h"
#include "include/defs.h"

#include <stdio.h>
#include <string.h>


/*
 * Set the default values for all the variables
 */
static void setDefaults(settings_t *s) {
    s->LOAD_DIR    = ".";
    s->CONFIG_FILE = "l33t_server.conf";
    s->MAX_THREADS = 7; 
    s->PORT_NUMBER = 1337; // l33t
}

/*
 * Initialize internal server parameters
 */
int init_settings(settings_t *s, int argc, char** argv) {
    ConfigFile* configFile;

    VPRINTF(("** Reading Config File **\n\n"));

    setDefaults(s);

    configFile = loadFile(s->CONFIG_FILE);

    while (nextSet(configFile)) {

        if (!strcmp(configFile->currentParamter, "LOAD_DIR")) {
            VPRINTF(("*** Read LOAD_FILE Value: %s\n",configFile->currentValue));
            s->LOAD_DIR = malloc(strlen(configFile->currentValue)+1);
            strcpy(s->LOAD_DIR, configFile->currentValue);

        } else if(!strcmp(configFile->currentParamter, "CONFIG_FILE")) {
            VPRINTF(("*** Read CONFIG_FILE Value: %s\n",configFile->currentValue));
            s->CONFIG_FILE = malloc(strlen(configFile->currentValue)+1);
            strcpy(s->CONFIG_FILE, configFile->currentValue);

        } else if(!strcmp(configFile->currentParamter, "MAX_THREADS")) {
            s->MAX_THREADS = atoi(configFile->currentValue);
            
            // In case some idiot tries to set the MAX_THREADS <=0 
            if (s->MAX_THREADS < 1) {
                s->MAX_THREADS = 1;
            }

            VPRINTF(("*** Read MAX_THREADS Value: %d\n",s->MAX_THREADS));

        } else if(!strcmp(configFile->currentParamter, "PORT_NUMBER")) {
            s->PORT_NUMBER = atoi(configFile->currentValue);
            VPRINTF(("*** Read PORT_NUMBER Value: %d\n",s->PORT_NUMBER));
        
        } else {
            printf("**** Illegal Parameter Exception in Config File:\n");
            printf("****   \"%s:%s\"\n", configFile->currentParamter, configFile->currentValue);
            printf("****  is not a legal Configuration Parameter.\n");
        }
    }

    VPRINTF(("\n** Done Reading Config File **\n\n"));

    return 0;
}

